const fs = require('fs')

module.exports = new Proxy({}, {
    get(that, key) {
        if (that.__inner__ === undefined) {
            try {
                let content = fs.readFileSync(`${process.env.HOME}/.config/crepo/config.json`)
                content = content.toString().replace(/\$HOME/g, `${process.env.HOME}`)
                that.__inner__ = JSON.parse(content)
            } catch (err) {
                console.error('Read Config: ' + err.message)
                process.exit(err.errno)
            }
        }

        if (key === 'repos') {
            if (that.__repos__ === undefined) {
                that.__repos__ = []
                let foreachTree = (value, key = '') => {
                    for (let k in value) {
                        if (value[k] === null ||
                            value[k].constructor !== Object) {
                            value.url = key
                            that.__repos__.push(value)
                            return
                        }
                    }

                    for (let k in value) {
                        foreachTree(value[k], key === '' ? k : `${key}/${k}`)
                    }
                }
                foreachTree(that.__inner__.repos)

                for (let repo of that.__repos__) {
                    if (repo.name === undefined) {
                        repo.name = repo.url.substr(repo.url.lastIndexOf('/') + 1)
                    }

                    if (repo.name.substr(repo.name.length - 4) !== ".git") {
                        repo.name += ".git"
                    }

                    repo.path = that.__inner__.repo_dir + '/' + repo.name
                }
            }

            return that.__repos__
        }
        return that.__inner__[key]
    },
})
